package com.hmz.backend.service.Impl.friend;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmz.backend.entity.ChatRoom;
import com.hmz.backend.entity.Friend;
import com.hmz.backend.mapper.ChatRoomMapper;
import com.hmz.backend.mapper.FriendMapper;
import com.hmz.backend.service.friend.DeleteFriendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class DeleteFriendServiceImpl implements DeleteFriendService {
    @Autowired
    private FriendMapper friendMapper;
    @Autowired
    private ChatRoomMapper chatRoomMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public JSONObject deleteFriend(JSONObject data) {
        int userId = (int) data.get("userId");
        int friendId = (int) data.get("friendId");
        QueryWrapper<Friend> friendQueryWrapper = new QueryWrapper<>();
        friendQueryWrapper.eq("user_id",userId).eq("friend_id",friendId).or(i -> i.eq("user_id",friendId).eq("friend_id",friendId));
        friendMapper.delete(friendQueryWrapper);
        QueryWrapper<ChatRoom> chatRoomQueryWrapper = new QueryWrapper<>();
        chatRoomQueryWrapper.like(true,"person","user"+userId).like(true,"person","user"+friendId).isNull("chat_room_name");
        try {
            int chatRoomId = chatRoomMapper.selectOne(chatRoomQueryWrapper).getId();
            chatRoomMapper.delete(chatRoomQueryWrapper);
            redisTemplate.delete("message"+chatRoomId);
        } catch (Exception e) {
            System.out.println(e);
            return new JSONObject().set("message","删除失败");
        }
        return new JSONObject().set("message","删除成功");
    }
}
